<template>
  <div class="menu-wrapper">
    <template v-for="(item, index) in menu">
      <el-menu-item
        v-if="validatenull(item[childrenKey]) && vaildRoles(item)"
        :index="item[pathKey]"
        @click="open(item)"
        :key="item[labelKey]"
        :class="{ 'is-active': vaildActive(item, index) }"
      >
        <i :class="item[iconKey]"></i>
        <span slot="title" :alt="item[pathKey]">{{ generateTitle(item) }}</span>
      </el-menu-item>
      <el-submenu v-else-if="!validatenull(item[childrenKey]) && vaildRoles(item)" :index="item[pathKey]" :key="item[labelKey]">
        <template slot="title">
          <i :class="item[iconKey]"></i>
          <span slot="title" :class="{ 'el-menu--display': collapse && first }">{{ generateTitle(item) }}</span>
        </template>
        <template v-for="(child, cindex) in item[childrenKey]">
          <el-menu-item
            :index="(child[pathKey], cindex)"
            @click="open(child)"
            :class="{ 'is-active': vaildActive(child, cindex) }"
            v-if="validatenull(child[childrenKey])"
            :key="child[labelKey]"
          >
            <i :class="child[iconKey]"></i>
            <span slot="title">{{ generateTitle(child) }}</span>
          </el-menu-item>
          <sidebar-item v-else :menu="[child]" :key="cindex" :props="props" :screen="screen" :collapse="collapse"></sidebar-item>
        </template>
      </el-submenu>
    </template>

    <!-- <el-dialog :title="largeScreen.title" :visible.sync="largeScreen.visible" width="50%" :modal-append-to-body="true" :append-to-body="true" @close="closeDialog">
      <avue-form ref="form" :option="option" v-model="form" @submit="submit"></avue-form>
    </el-dialog> -->

    <el-drawer :title="largeScreen.title" :visible.sync="largeScreen.visible" :append-to-body="true" direction="rtl" size="50%" @close="closeDialog">
      <avue-form ref="form" :option="option" v-model="form" @submit="submit"></avue-form>
    </el-drawer>
  </div>
</template>
<script>
import { mapGetters } from 'vuex';
import { isURL, validatenull } from '@/util/validate';
import { getToken } from '@/util/auth';
import config from './config.js';
import { largeScreenConfigList, largeScreenConfigOption } from './largeScreenConfigList.js';
export default {
  name: 'sidebarItem',
  data() {
    return {
      config: config,
      largeScreen: {
        visible: false,
        title: '',
        path: ''
      },
      option: {
        submitText: '完成',
        span: 24,
        column: []
      },
      form: {}
    };
  },
  props: {
    menu: {
      type: Array
    },
    screen: {
      type: Number
    },
    first: {
      type: Boolean,
      default: false
    },
    props: {
      type: Object,
      default: () => {
        return {};
      }
    },
    collapse: {
      type: Boolean
    }
  },
  watch: {
    nowTagValue(val) {
      this.$emit('getOpeneds', val);
    }
  },
  created() {},
  mounted() {},
  computed: {
    ...mapGetters(['roles']),
    labelKey() {
      return this.props.label || this.config.propsDefault.label;
    },
    pathKey() {
      return this.props.path || this.config.propsDefault.path;
    },
    iconKey() {
      return this.props.icon || this.config.propsDefault.icon;
    },
    childrenKey() {
      return this.props.children || this.config.propsDefault.children;
    },
    isOpenKey() {
      return this.props.isOpen || this.config.propsDefault.isOpen;
    },
    nowTagValue() {
      return this.$router.$avueRouter.getValue(this.$route);
    }
  },
  methods: {
    generateTitle(item) {
      return this.$router.$avueRouter.generateTitle(item[this.labelKey], (item.meta || {}).i18n);
    },
    vaildActive(item, index) {
      if (this.validIsOpen(item)) {
        return false;
      }
      const groupFlag = (item['group'] || []).some((ele) => this.$route.path.includes(ele));
      return this.nowTagValue === item[this.pathKey] || groupFlag;
    },
    vaildRoles(item) {
      item.meta = item.meta || {};
      return item.meta.roles ? item.meta.roles.includes(this.roles) : true;
    },
    validatenull(val) {
      return validatenull(val);
    },
    validIsOpen(item) {
      if (item[this.isOpenKey] === 2 && isURL(item[this.pathKey])) {
        return true;
      }
    },
    open(item) {
      const that = this;
      if (that.screen <= 1) that.$store.commit('SET_COLLAPSE');
      // 打开新窗口
      if (that.validIsOpen(item)) {
        // 看板
        let path = item[this.pathKey];
        let isKanBan = path.startsWith(`${that.website.avueDataUrl}/view/`);

        if (largeScreenConfigList.includes(item.name)) {
          that.openDvpDrawer(item);
        } else {
          this.formatterKanBanPath(path);
        }

        // if (isKanBan) {
        //   this.formatterKanBanPath(path);
        // } else {
        //   window.open(path);
        // }
      } else {
        this.$router.$avueRouter.group = item.group;
        this.$router.$avueRouter.meta = item.meta;
        this.$router.push({
          path: this.$router.$avueRouter.getPath(
            {
              name: item[this.labelKey],
              src: item[this.pathKey]
            },
            item.meta
          ),
          query: item.query
        });
      }
    },
    openDvpDrawer(item) {
      const that = this;
      that.largeScreen.visible = true;
      that.largeScreen.path = item[this.pathKey];
      that.largeScreen.title = item.name + '配置';
      that.option.column = largeScreenConfigOption[item.name];
    },
    formatterKanBanPath(path) {
      let siteId = localStorage.getItem('saber-siteId');
      let tenantId = JSON.parse(localStorage.getItem('saber-tenantId') || '{}').content;
      let userId = JSON.parse(localStorage.getItem('saber-userInfo') || '{}').content.user_id;
      let token = 'bearer ' + getToken();
      path = path + '?siteId=' + siteId + '&tenantId=' + tenantId + '&userId=' + userId + '&token=' + token;
      window.open(path);
    },
    submit() {
      this.$refs.form.validate((valid, done) => {
        if (valid) {
          let path = this.largeScreen.path;
          let siteId = localStorage.getItem('saber-siteId');
          let tenantId = JSON.parse(localStorage.getItem('saber-tenantId') || '{}').content;
          let userId = JSON.parse(localStorage.getItem('saber-userInfo') || '{}').content.user_id;
          let token = 'bearer ' + getToken();
          let str = '';
          Object.keys(this.form).forEach((key) => {
            if (key == 'daterange') {
              let [startDate, endDate] = this.form[key];
              str += '&startDate=' + startDate + '&endDate=' + endDate;
            } else {
              str += `&${key}=${this.form[key]}`;
            }
          });
          path = path + '?siteId=' + siteId + '&tenantId=' + tenantId + '&userId=' + userId + str + '&token=' + token;
          window.open(path);
          done();
        } else {
          return false;
        }
      });
    },
    closeDialog() {
      this.$refs.form.resetForm();
    }
  }
};
</script>
